import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:sjx/repository/model/withdrawal_model.dart';
import 'package:sjx/utils/sp_utils.dart';
import 'package:sjx/repository/model/user_model.dart';
import 'package:sjx/repository/sjx_api.dart';

import '../../../route/route_utils.dart';
import '../../../route/routes.dart';

class WithdrawalPage extends StatefulWidget {
  const WithdrawalPage({super.key});

  @override
  State<WithdrawalPage> createState() => _WithdrawalPageState();
}

class _WithdrawalPageState extends State<WithdrawalPage> {
  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  bool _isLoading = true;
  bool _isSubmitting = false;
  bool _isCodeSending = false;
  int _countdown = 0;
  Timer? _timer;

  double _availableAmount = 0.0;
  WithdrawalModel? _withdrawalAccount;
  int? _selectedAmountIndex;

  bool get _hasBoundAccount => _withdrawalAccount?.isBound == true;
  bool get _canSubmit => _selectedAmountIndex != null && (_hasBoundAccount || _codeController.text.isNotEmpty);

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  void dispose() {
    _accountController.dispose();
    _nameController.dispose();
    _codeController.dispose();
    _timer?.cancel();
    super.dispose();
  }

  Future<void> _loadData() async {
    try {
      setState(() {
        _isLoading = true;
      });

      // 并行加载数据
      await Future.wait([
        _loadAvailableAmount(),
        _loadWithdrawalAccount(),
      ]);

    } catch (e) {
      _showMessage('加载失败: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _loadAvailableAmount() async {
    try {
      final amount = await SJXApi.instance().userAccount();
      if (mounted) {
        setState(() {
          _availableAmount = amount;
        });
      }
    } catch (e) {
      _showMessage('获取余额失败: $e');
    }
  }

  Future<void> _loadWithdrawalAccount() async {
    try {
      final account = await SJXApi.instance().userWithdrawAccountInfo();
      if (mounted) {
        setState(() {
          _withdrawalAccount = account;
        });

        // 如果已绑定账户，自动填充信息
        if (account.isBound) {
          _accountController.text = account.account ?? '';
          _nameController.text = account.realName ?? '';
        }
      }
    } catch (e) {
      _showMessage('获取账户信息失败: $e');
    }
  }

  void _showMobileNotBoundDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提示'),
          content: const Text('需要重新登录后进行绑定手机号，才能进行提现操作'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                Navigator.of(context).pop();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _logoutAndRelogin();
              },
              child: const Text('重新登录'),
            ),
          ],
        );
      },
    );
  }

  void _logoutAndRelogin() {
    // 清除用户数据并跳转到登录页
    SpUtils.clearUserData();
    // 这里应该跳转到登录页面
    // Navigator.pushAndRemoveUntil(...)
  }

  void _startCountdown() {
    _countdown = 60;
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted) {
        setState(() {
          if (_countdown > 0) {
            _countdown--;
          } else {
            _timer?.cancel();
          }
        });
      }
    });
  }

  Future<void> _sendVerificationCode() async {
    try {
      setState(() {
        _isCodeSending = true;
      });

      final user = await SpUtils.getUserData();
      if (user == null || user.mobile.isEmpty) {
        _showMessage('用户未绑定手机号');
        return;
      }

      await SJXApi.instance().phoneCode(user.mobile);
      _startCountdown();
      _showMessage('验证码已发送');
    } catch (e) {
      _showMessage('发送失败: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isCodeSending = false;
        });
      }
    }
  }

  Future<void> _submitWithdrawal() async {
    if (_selectedAmountIndex == null) {
      _showMessage('请选择提现金额');
      return;
    }

    if (!_hasBoundAccount) {
      if (_accountController.text.isEmpty) {
        _showMessage('请输入支付宝账号');
        return;
      }
      if (_nameController.text.isEmpty) {
        _showMessage('请输入支付宝认证姓名');
        return;
      }
      if (_codeController.text.isEmpty) {
        _showMessage('请输入验证码');
        return;
      }
    }

    try {
      setState(() {
        _isSubmitting = true;
      });
      final selectedOption = _withdrawalAccount!.withdrawOptions[_selectedAmountIndex!];

      // 如果未绑定账户，需要验证验证码
      if (!_hasBoundAccount) {
        await SJXApi.instance().applyWithdraw({
          "channelAccount":_accountController.text,
          "realName":_nameController.text,
          "verifyCode":_codeController.text,
          "withdrawAmount": selectedOption.optionValue
        });
      } else {
        final user = await SpUtils.getUserData();
        await SJXApi.instance().applyWithdrawNotCode({
          "platformId":user?.platformId,
          "withdrawAmount": selectedOption.optionValue
        });
      }
      // 跳转到提现成功页面
      _navigateToSuccessPage();

    } on DioException catch (e) {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    } catch (e) {
      _showMessage('提现失败: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  void _navigateToSuccessPage() {
    // 跳转到提现成功页面
    RouteUtils.pushForNamed(context, RoutePath.withdrawal_success);
  }

  void _navigateToRecordPage() {
    // 跳转到提现记录页面
    RouteUtils.pushForNamed(context, RoutePath.withdrawal_record);
  }

  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('提现'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          TextButton(
            onPressed: _navigateToRecordPage,
            child: const Text(
              '提现记录',
              style: TextStyle(
                color: Color(0xFF262626),
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
      backgroundColor: Colors.white,
      body: _isLoading
          ? _buildLoading()
          : _buildContent(),
    );
  }

  Widget _buildLoading() {
    return const Center(
      child: CircularProgressIndicator(),
    );
  }

  Widget _buildContent() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 提现至支付宝标题
          _buildSectionTitle('提现至支付宝'),

          // 支付宝账户信息
          _buildAccountInfoSection(),

          // 手机验证部分
          if (!_hasBoundAccount) _buildVerificationSection(),

          // 选择提现金额
          _buildAmountSelectionSection(),

          // 温馨提示
          _buildTipsSection(),

          // 确认按钮
          _buildSubmitButton(),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Row(
        children: [
          Image.asset(
            'assets/images/zhifubao_icon.png',
            width: 20,
            height: 20,
          ),
          const SizedBox(width: 8),
          Text(
            title,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF262626),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAccountInfoSection() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: const Color(0xFFF8F9FA),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Column(
        children: [
          // 支付宝账号
          _buildFormItem(
            label: '支付宝账号',
            controller: _accountController,
            hintText: '请输入支付宝账号',
            enabled: !_hasBoundAccount, // 已绑定账户不可编辑
          ),
          const Divider(height: 1, indent: 15),
          // 真实姓名
          _buildFormItem(
            label: '真实姓名',
            controller: _nameController,
            hintText: '请输入支付宝实名认证姓名',
            enabled: !_hasBoundAccount, // 已绑定账户不可编辑
          ),
        ],
      ),
    );
  }

  Widget _buildVerificationSection() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: const Color(0xFFF8F9FA),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Padding(
            padding: EdgeInsets.all(16),
            child: Text(
              '为保证资金安全需通过短信验证',
              style: TextStyle(
                fontSize: 12,
                color: Color(0xFF666666),
              ),
            ),
          ),
          const Divider(height: 1),
          // 手机号显示
          _buildPhoneDisplay(),
          const Divider(height: 1),
          // 验证码输入
          _buildVerificationCodeItem(),
        ],
      ),
    );
  }

  Widget _buildPhoneDisplay() {
    return FutureBuilder<UserModel?>(
      future: SpUtils.getUserData(),
      builder: (context, snapshot) {
        String phoneText = '未绑定手机号';
        if (snapshot.hasData && snapshot.data?.mobile.isNotEmpty == true) {
          final mobile = snapshot.data!.mobile;
          if (mobile.length >= 11) {
            phoneText = '${mobile.substring(0, 3)}****${mobile.substring(7)}';
          } else {
            phoneText = mobile;
          }
        }

        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
          child: Row(
            children: [
              const SizedBox(
                width: 80,
                child: Text(
                  '手机号',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFF262626),
                  ),
                ),
              ),
              const SizedBox(width: 16),
              Text(
                phoneText,
                style: const TextStyle(
                  fontSize: 14,
                  color: Color(0xFF262626),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildVerificationCodeItem() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      child: Row(
        children: [
          const SizedBox(
            width: 80,
            child: Text(
              '短信验证码',
              style: TextStyle(
                fontSize: 14,
                color: Color(0xFF262626),
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: TextField(
              controller: _codeController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                border: InputBorder.none,
                hintText: '请输入验证码',
                hintStyle: TextStyle(
                  color: Color(0xFFBFBFBF),
                  fontSize: 14,
                ),
                contentPadding: EdgeInsets.zero,
              ),
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF262626),
              ),
            ),
          ),
          const SizedBox(width: 16),
          SizedBox(
            width: 100,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: _countdown > 0
                    ? Colors.grey.shade300
                    : Theme.of(context).colorScheme.primary,
                foregroundColor: _countdown > 0 ? Colors.grey : Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(4),
                ),
                padding: const EdgeInsets.symmetric(vertical: 8),
                elevation: 0,
              ),
              onPressed: (_isCodeSending || _countdown > 0)
                  ? null
                  : _sendVerificationCode,
              child: _isCodeSending
                  ? const SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation(Colors.white),
                ),
              )
                  : Text(
                _countdown > 0 ? '已发送($_countdown)' : '获取验证码',
                style: TextStyle(
                  fontSize: 12,
                  color: _countdown > 0
                      ? Colors.grey
                      : Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAmountSelectionSection() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '选择提现金额',
                style: TextStyle(
                  fontSize: 12,
                  color: Color(0xFF666666),
                ),
              ),
              Text(
                '可提现金额：${_availableAmount.toStringAsFixed(2)}元',
                style: const TextStyle(
                  fontSize: 13,
                  color: Color(0xFF262626),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          if (_withdrawalAccount != null)
            _buildAmountGrid(),
        ],
      ),
    );
  }

  Widget _buildAmountGrid() {
    final options = _withdrawalAccount!.withdrawOptions;
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        childAspectRatio: 2.5,
      ),
      itemCount: options.length,
      itemBuilder: (context, index) {
        final option = options[index];
        final isSelected = _selectedAmountIndex == index;

        return ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: isSelected ? const Color(0xFFFFECF1) : const Color(0xFFF5F5F5),
            foregroundColor: isSelected ? Theme.of(context).colorScheme.primary : const Color(0xFF262626),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(4),
            ),
            elevation: 0,
            side: BorderSide(
              color: isSelected ? Theme.of(context).colorScheme.primary : Colors.transparent,
            ),
          ),
          onPressed: () {
            setState(() {
              _selectedAmountIndex = index;
            });
          },
          child: Text(
            option.optionDisplay,
            style: TextStyle(
              fontSize: 14,
              color: isSelected ? Theme.of(context).colorScheme.primary : const Color(0xFF262626),
            ),
          ),
        );
      },
    );
  }

  Widget _buildTipsSection() {
    return Container(
      margin: const EdgeInsets.only(bottom: 24),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: const Color(0xFFE6F7FF),
        borderRadius: BorderRadius.circular(6),
        border: Border.all(
          color: const Color(0xFF91D5FF),
          width: 1,
        ),
      ),
      child: const Text(
        '温馨提示：为保证提现成功，请确保输入的真实姓名是支付宝账号的实名认证姓名，否则将会导致提现失败。',
        style: TextStyle(
          fontSize: 12,
          color: Color(0xFF1890FF),
          height: 1.4,
        ),
      ),
    );
  }

  Widget _buildSubmitButton() {
    return SizedBox(
      width: double.infinity,
      height: 44,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: _canSubmit
              ? Theme.of(context).colorScheme.primary
              : Colors.grey.shade400,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(22),
          ),
          elevation: 0,
        ),
        onPressed: _canSubmit && !_isSubmitting ? _submitWithdrawal : null,
        child: _isSubmitting
            ? const SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            valueColor: AlwaysStoppedAnimation(Colors.white),
          ),
        )
            : Text(
          _hasBoundAccount ? '确认提现' : '验证并提现',
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  Widget _buildFormItem({
    required String label,
    required TextEditingController controller,
    required String hintText,
    bool enabled = true,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF262626),
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: TextField(
              controller: controller,
              enabled: enabled,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: hintText,
                hintStyle: const TextStyle(
                  color: Color(0xFFBFBFBF),
                  fontSize: 14,
                ),
                contentPadding: EdgeInsets.zero,
              ),
              style: TextStyle(
                fontSize: 14,
                color: enabled ? const Color(0xFF262626) : Colors.grey,
              ),
            ),
          ),
        ],
      ),
    );
  }
}